﻿using System;
using System.Runtime.CompilerServices;
using Launch;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace LP
{
    public sealed class SceneMgr : AbsMgr
    {
        /*
         * 游戏是单场景模式所以游戏要在场景切换的时候卸载上一个场景的AbsModule
         */
        //当前场景模块
        private AbsModule curSceneModule;

        public override void OnInit()
        {
            base.OnInit();
            Global.SceneEventHandler.RegHandler(EScene.ShowLaunchScene, ShowLaunchScene, TokenSource.Token);
        }

        private void ShowLaunchScene(ITuple tuple)
        {
            if (curSceneModule != null)
            {
                GLModuleMgr.Ins.UnRegModule(curSceneModule);
            }

            curSceneModule = GLModuleMgr.Ins.RegModule<LaunchModule>();
        }


        private void LoadScene<T>(string sceneAbPath, Action cb = null) where T : AbsModule
        {
            Global.ResMgrIns.LoadSceneAsync(sceneAbPath, UpdateSceneLoadingPanelProcess, () =>
            {
                Global.SysEventHandler.Notify(ESys.OnSceneChange);
                Global.ResMgrIns.ForceUnloadAssets();
                // 场景加载完成
                if (curSceneModule != null)
                {
                    GLModuleMgr.Ins.UnRegModule(curSceneModule);
                }

                curSceneModule = GLModuleMgr.Ins.RegModule<T>();
                cb?.Invoke();
            });
        }

        /// <summary>
        /// 场景是否处于激活状态
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private bool IsActive(string name)
        {
            return SceneManager.GetActiveScene().name == name;
        }

        private void UpdateSceneLoadingPanelProcess(float process)
        {
            if (process >= 0.98)
            {
                process = 1f;
            }

            Debug.Log($"场景加载进度：{process}");
        }
    }
}